/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cognitivetest.toolLibs;

import static java.awt.Frame.NORMAL;
import java.util.concurrent.TimeUnit;
import javax.swing.JFrame;
import matlabcontrol.MatlabConnectionException;
import matlabcontrol.MatlabInvocationException;
import matlabcontrol.MatlabProxy;
import matlabcontrol.MatlabProxyFactory;

/**
 *
 * @author Libra
 */
public class MatlabControlInterface {

    private static MatlabProxy proxy;
    private static JFrame mainUI;

    public static boolean init(JFrame ui) {
        mainUI = ui;
        if (proxy != null && proxy.isConnected()) {
            return true;
        } else {
            try {
                MatlabProxyFactory factory = new MatlabProxyFactory();
                proxy = factory.getProxy();
                return true;
            } catch (MatlabConnectionException ex) {
                System.out.println(ex.toString());
                return false;
            }
        }
    }

    public static String send(String s) {
        try {
            proxy.eval(s);
            return "";
        } catch (MatlabInvocationException | NullPointerException ex) {
            return ex.toString() + ". Is Matlab running?";
        }
    }

    public static void disconnect() {
        proxy.disconnect();
    }

    public static void returnUI(int time) {
        try {
            TimeUnit.SECONDS.sleep(time);
            mainUI.setVisible(true);
            mainUI.setState(NORMAL);
            mainUI.toFront();
        } catch (InterruptedException ex) {
//            Logger.getLogger(MainUI.class.getName()).log(Level.SEVERE, null, ex);
//            message(ex.toString());
        }
    }
}
